import 'dart:convert';
import 'dart:io';

import 'package:animation_wrappers/animations/faded_slide_animation.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:xiaofanshu_flutter/config/text_field_config.dart';
import 'package:xiaofanshu_flutter/controller/publish_notes_controller.dart';
import 'package:xiaofanshu_flutter/static/custom_color.dart';
import 'package:xiaofanshu_flutter/utils/comment_util.dart';

import '../../model/emoji.dart';
import '../../static/emoji_map.dart';
import '../../utils/Adapt.dart';

class PublishNotes extends StatefulWidget {
  const PublishNotes({super.key});

  @override
  State<PublishNotes> createState() => _PublishNotesState();
}

class _PublishNotesState extends State<PublishNotes> {
  PublishNotesController publishNotesController = Get.find();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }



  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        bool shouldPop = false;
        await Get.defaultDialog(
          title: "提示",
          middleText: "是否保存草稿",
          actions: [
            TextButton(
              onPressed: () {
                publishNotesController.saveDraft();
                shouldPop = true;
                Get.back();
              },
              child: const Text("保存"),
            ),
            TextButton(
              onPressed: () {
                shouldPop = true;
                Get.back();
              },
              child: const Text("不保存"),
            ),
          ],
        );
        return shouldPop;
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
            backgroundColor: Colors.white,
            leading: IconButton(
              splashColor: Colors.transparent,
              highlightColor: Colors.transparent,
              icon: const Icon(
                Icons.arrow_back_ios,
                color: CustomColor.unselectedColor,
                size: 25,
              ),
              onPressed: () {
                Get.back();
              },
            ),
            leadingWidth: 28,
            title: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                // AI续写/AI辅助创作按钮
                Obx(() => GestureDetector(
                  onTap: () async {
                    if (publishNotesController.isContinuation.value) {
                      // 续写模式：显示弹窗选择
                      _showAiContinuationDialog();
                    } else {
                      // 非续写模式：直接跳转到AI创作页面
                      final result = await Get.toNamed('/ai/creation', arguments: {
                        'isContinuation': false,
                      });
                      
                      // 处理返回结果
                      if (result != null && result['adopted'] == true) {
                        _handleAiGeneratedContent(result['content']);
                      }
                    }
                  },
                  child: Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      gradient: LinearGradient(
                        colors: [
                          CustomColor.primaryColor.withOpacity(0.8),
                          CustomColor.primaryColor,
                        ],
                        begin: Alignment.topLeft,
                        end: Alignment.bottomRight,
                      ),
                      borderRadius: BorderRadius.circular(20),
                      boxShadow: [
                        BoxShadow(
                          color: CustomColor.primaryColor.withOpacity(0.3),
                          blurRadius: 8,
                          offset: const Offset(0, 2),
                        ),
                      ],
                    ),
                    child: Row(
                      children: [
                        const Icon(
                          Icons.auto_awesome,
                          color: Colors.white,
                          size: 16,
                        ),
                        const SizedBox(width: 4),
                        Text(
                          publishNotesController.isContinuation.value ? 'AI续写' : 'AI创作',
                          style: const TextStyle(
                            color: Colors.white,
                            fontSize: 13,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                      ],
                    ),
                  ),
                )),
                const SizedBox(width: 10),
                GestureDetector(
                  onTap: () {
                    Get.dialog(
                      const AlertDialog(
                        title: Text("发帖小提示"),
                        content: Text('发帖小提示内容'),
                      ),
                    );
                  },
                  child: const Icon(
                    Icons.tips_and_updates_outlined,
                    color: CustomColor.unselectedColor,
                    size: 25,
                  ),
                ),
              ],
            )),
        body: Obx(
          () => SizedBox(
            height: MediaQuery.of(context).size.height,
            child: Stack(
              children: [
                SingleChildScrollView(
                  child: Column(
                    children: [
                      _resource(),
                      _titleInput(),
                      _contentInput(),
                      _toolBar(),
                      _atUser(),
                      _emoji(),
                      // 续写模式下显示继承的地址信息，否则显示选择器
                      Obx(() => publishNotesController.isContinuation.value
                          ? _inheritedLocation()
                          : _selectLocation()),
                      // 续写模式下显示继承的分类信息，否则显示选择器
                      Obx(() => publishNotesController.isContinuation.value
                          ? _inheritedCategory()
                          : _selectCategory()),
                      // 续写选项（非续写模式下显示）
                      _allowContinuationOption(),
                      _setPermission(),
                    ],
                  ).paddingOnly(bottom: 60),
                ),
                Positioned(
                  bottom: 0,
                  left: 0,
                  right: 0,
                  child: _publishButton(),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _resource() {
    return publishNotesController.type.value == 0
        ? SizedBox(
            height: 100,
            child: ListView.builder(
              scrollDirection: Axis.horizontal,
              padding: const EdgeInsets.only(
                  left: 15, right: 15, top: 10, bottom: 10),
              itemCount: publishNotesController.files.length + 1,
              itemBuilder: (BuildContext context, int index) {
                return index == publishNotesController.files.length
                    ? GestureDetector(
                        onTap: () async {
                          // 添加图片
                          List<AssetEntity>? assets =
                              await AssetPicker.pickAssets(
                            context,
                            pickerConfig: AssetPickerConfig(
                              maxAssets:
                                  9 - publishNotesController.files.length,
                              requestType: RequestType.image,
                            ),
                          );
                          if (assets != null) {
                            for (int i = 0; i < assets.length; i++) {
                              File? file = await assets[i].file;
                              if (file != null) {
                                publishNotesController.files.add(file);
                              }
                            }
                          }
                        },
                        child: Container(
                          width: 80,
                          height: 80,
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(10),
                            color: CustomColor.unselectedColor.withOpacity(0.2),
                          ),
                          child: const Icon(
                            Icons.add,
                            color: CustomColor.unselectedColor,
                          ),
                        ).paddingOnly(right: 10),
                      )
                    : Stack(
                        children: [
                          GestureDetector(
                            onTap: () {
                              List<File> files = publishNotesController.files;
                              List<String> urls = [];
                              for (int i = 0; i < files.length; i++) {
                                urls.add(files[i].path);
                              }
                              Get.toNamed(
                                '/image/simple/pre',
                                arguments: urls,
                                parameters: {'index': index.toString()},
                              );
                            },
                            child: Container(
                              width: 80,
                              height: 80,
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                                image: DecorationImage(
                                  image: FileImage(
                                      publishNotesController.files[index]),
                                  fit: BoxFit.cover,
                                ),
                              ),
                            ),
                          ),
                          Positioned(
                            top: 0,
                            right: 0,
                            child: GestureDetector(
                              onTap: () {
                                publishNotesController.files.removeAt(index);
                              },
                              child: Container(
                                width: 15,
                                height: 15,
                                decoration: BoxDecoration(
                                  color: Colors.red.withOpacity(0.8),
                                  borderRadius: const BorderRadius.only(
                                    topRight: Radius.circular(8),
                                    bottomLeft: Radius.circular(3),
                                  ),
                                ),
                                child: const Center(
                                  child: Icon(
                                    Icons.close,
                                    color: Colors.white,
                                    size: 10,
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ).paddingOnly(right: 10);
              },
            ),
          )
        : Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                height: 120,
                width: 120,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(10),
                  image: DecorationImage(
                    image: FileImage(publishNotesController.cover.value),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              Row(
                children: [
                  GestureDetector(
                    onTap: () async {
                      Get.toNamed(
                        '/video/simple/pre',
                        arguments: publishNotesController.video.value.path,
                      );
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: CustomColor.unselectedColor.withOpacity(0.2),
                      ),
                      child: const Text(
                        "预览视频",
                        style: TextStyle(
                          color: CustomColor.unselectedColor,
                          fontSize: 12,
                        ),
                      ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
                    ).paddingOnly(right: 10),
                  ),
                  GestureDetector(
                    onTap: () async {
                      List<AssetEntity>? assets = await AssetPicker.pickAssets(
                        context,
                        pickerConfig: const AssetPickerConfig(
                          maxAssets: 1,
                          requestType: RequestType.image,
                        ),
                      );
                      if (assets != null && assets.isNotEmpty) {
                        File? file = await assets[0].file;
                        if (file != null) {
                          publishNotesController.cover.value = file;
                        }
                      }
                    },
                    child: Container(
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(10),
                        color: CustomColor.unselectedColor.withOpacity(0.2),
                      ),
                      child: const Text(
                        "设置其他封面",
                        style: TextStyle(
                          color: CustomColor.unselectedColor,
                          fontSize: 12,
                        ),
                      ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
                    ).paddingOnly(right: 10),
                  ),
                ],
              ).marginOnly(top: 10),
            ],
          ).paddingOnly(left: 15, right: 15, top: 10, bottom: 10);
  }

  Widget _titleInput() {
    return Container(
      padding: const EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: TextField(
        style: const TextStyle(
          fontSize: 20,
        ),
        enableInteractiveSelection: true,
        selectionControls: CustomTextSelectionControls(),
        maxLength: 20,
        cursorColor: CustomColor.primaryColor,
        cursorWidth: 3,
        decoration: InputDecoration(
          hintText: '添加标题',
          hintStyle: const TextStyle(
            color: CustomColor.unselectedColor,
            fontSize: 20,
          ),
          border: InputBorder.none,
          suffixIcon: IconButton(
            onPressed: () {
              publishNotesController.titleController.clear();
            },
            icon: const Icon(
              Icons.close,
              color: CustomColor.unselectedColor,
              size: 20,
            ),
          ),
        ),
        maxLines: 1,
        controller: publishNotesController.titleController,
      ),
    );
  }

  Widget _contentInput() {
    return Container(
      padding: const EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
      child: ExtendedTextField(
        specialTextSpanBuilder: MySpecialTextSpanBuilder(),
        controller: publishNotesController.contentController,
        maxLines: 5,
        minLines: 1,
        cursorColor: CustomColor.primaryColor,
        cursorWidth: 3,
        maxLength: 200000,
        selectionControls: CustomTextSelectionControls(),
        decoration: const InputDecoration(
          hintText: '添加正文',
          helperText: '最多输入200000字，添加话题时需要以空格结尾哦',
          helperStyle: TextStyle(
            color: CustomColor.unselectedColor,
            fontSize: 12,
          ),
          hintStyle: TextStyle(
            color: CustomColor.unselectedColor,
            fontSize: 16,
          ),
          border: InputBorder.none,
        ),
        style: const TextStyle(
          fontSize: 16,
        ),
      ),
    );
  }

  Widget _toolBar() {
    return Container(
      padding: const EdgeInsets.only(left: 15, right: 15, top: 10, bottom: 10),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          GestureDetector(
            onTap: () {
              insertText(" #", publishNotesController.contentController);
            },
            child: Container(
              decoration: BoxDecoration(
                color: const Color(0xffe5e4e6).withOpacity(0.6),
                borderRadius: BorderRadius.circular(20),
              ),
              child: const Row(
                children: [
                  Icon(
                    Icons.group_work_outlined,
                    size: 16,
                  ),
                  Text(
                    "话题",
                    style: TextStyle(
                      fontSize: 14,
                    ),
                  ),
                ],
              ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
            ),
          ),
          GestureDetector(
            onTap: () {
              publishNotesController.isShowAtUser.value =
                  !publishNotesController.isShowAtUser.value;
            },
            child: Container(
              decoration: BoxDecoration(
                color: const Color(0xffe5e4e6).withOpacity(0.6),
                borderRadius: BorderRadius.circular(20),
              ),
              child: const Row(
                children: [
                  Icon(
                    Icons.alternate_email,
                    size: 16,
                  ),
                  Text(
                    "用户",
                    style: TextStyle(
                      fontSize: 14,
                    ),
                  ),
                ],
              ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
            ).marginOnly(left: 10),
          ),
          GestureDetector(
            onTap: () {
              publishNotesController.isShowEmoji.value =
                  !publishNotesController.isShowEmoji.value;
            },
            child: Container(
              decoration: BoxDecoration(
                color: const Color(0xffe5e4e6).withOpacity(0.6),
                borderRadius: BorderRadius.circular(20),
              ),
              child: const Row(
                children: [
                  Icon(
                    Icons.emoji_emotions_outlined,
                    size: 16,
                  ),
                  Text(
                    "表情",
                    style: TextStyle(
                      fontSize: 14,
                    ),
                  ),
                ],
              ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
            ).marginOnly(left: 10),
          ),
        ],
      ),
    );
  }

  Widget _atUser() {
    return publishNotesController.isShowAtUser.value
        ? FadedSlideAnimation(
            beginOffset: const Offset(-1, 0),
            endOffset: Offset.zero,
            fadeDuration: const Duration(milliseconds: 300),
            slideDuration: const Duration(milliseconds: 300),
            child: Container(
              height: 120,
              width: double.infinity,
              decoration: const BoxDecoration(
                color: Color(0xffe5e4e6),
              ),
              child: ListView.builder(
                controller: publishNotesController.attentionScrollController,
                padding: const EdgeInsets.only(
                  left: 10,
                  right: 10,
                  top: 8,
                ),
                scrollDirection: Axis.horizontal,
                itemCount: publishNotesController.attentionList.length,
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {
                      Map<String, String> map = {};
                      map['name'] = publishNotesController.attentionList[index]
                          ['nickname'];
                      map['id'] =
                          publishNotesController.attentionList[index]['userId'];
                      String attentionUserInfo = '@${jsonEncode(map)} ';
                      insertText(attentionUserInfo,
                          publishNotesController.contentController);
                    },
                    child: Column(
                      children: [
                        ClipOval(
                          child: Image.network(
                            publishNotesController.attentionList[index]
                                ['avatarUrl'],
                            width: 50,
                            height: 50,
                            fit: BoxFit.cover,
                          ),
                        ).paddingAll(10),
                        Text(
                          publishNotesController.attentionList[index]
                              ['nickname'],
                          style: const TextStyle(
                            fontSize: 12,
                            color: Color(0xff2b2b2b),
                          ),
                        ),
                      ],
                    ).marginOnly(right: 10),
                  );
                },
              ),
            ),
          )
        : const SizedBox();
  }

  /// 显示AI续写选择弹窗
  void _showAiContinuationDialog() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 顶部拖动条和标题
            Container(
              padding: const EdgeInsets.only(top: 8, bottom: 16),
              child: Column(
                children: [
                  // 拖动条
                  Container(
                    width: 40,
                    height: 4,
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2),
                    ),
                  ),
                  const SizedBox(height: 16),
                  // 标题
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const SizedBox(width: 48),
                      const Text(
                        '选择AI续写方式',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Color(0xff2b2b2b),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => Get.back(),
                        child: Container(
                          width: 48,
                          height: 48,
                          alignment: Alignment.center,
                          child: const Icon(
                            Icons.close,
                            size: 24,
                            color: Color(0xff8e8e93),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            
            // 选项列表
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
              child: Column(
                children: [
                  // AI续写剧情
                  GestureDetector(
                    onTap: () async {
                      Get.back();
                      final result = await Get.toNamed('/ai/creation', arguments: {
                        'isContinuation': true,
                        'parentNotesId': publishNotesController.parentNotesId,
                        'creationType': 0,
                      });
                      
                      // 处理返回结果
                      if (result != null && result['adopted'] == true) {
                        _handleAiGeneratedContent(result['content']);
                      }
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      margin: const EdgeInsets.only(bottom: 12),
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            CustomColor.primaryColor.withOpacity(0.08),
                            CustomColor.primaryColor.withOpacity(0.05),
                          ],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: CustomColor.primaryColor.withOpacity(0.2),
                          width: 1.5,
                        ),
                      ),
                      child: Row(
                        children: [
                          Container(
                            width: 48,
                            height: 48,
                            decoration: BoxDecoration(
                              gradient: LinearGradient(
                                colors: [
                                  CustomColor.primaryColor.withOpacity(0.8),
                                  CustomColor.primaryColor,
                                ],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(
                              Icons.auto_stories,
                              size: 24,
                              color: Colors.white,
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  'AI续写剧情',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                    color: Color(0xff2b2b2b),
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '让AI为你的故事续写精彩情节',
                                  style: TextStyle(
                                    fontSize: 13,
                                    color: Colors.grey[600],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            size: 16,
                            color: CustomColor.primaryColor.withOpacity(0.6),
                          ),
                        ],
                      ),
                    ),
                  ),
                  
                  // AI对话续写
                  GestureDetector(
                    onTap: () async {
                      Get.back();
                      // 先跳转到聊天页面与角色对话
                      // 注意：只传递 storyId，聊天页面会从后端加载故事信息
                      final result = await Get.toNamed('/sillytavern/chat', arguments: {
                        'storyId': publishNotesController.parentNotesId.toString(),
                        'storyTitle': '', // 留空，由后端加载
                        'storyContent': '', // 留空，由后端加载
                      });
                      
                      // 处理返回结果（从聊天页面返回的AI生成内容）
                      if (result != null && result['adopted'] == true) {
                        _handleAiGeneratedContent(result['content']);
                      }
                    },
                    behavior: HitTestBehavior.opaque,
                    child: Container(
                      padding: const EdgeInsets.all(16),
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          colors: [
                            const Color(0xFFFF9500).withOpacity(0.08),
                            const Color(0xFFFF9500).withOpacity(0.05),
                          ],
                          begin: Alignment.topLeft,
                          end: Alignment.bottomRight,
                        ),
                        borderRadius: BorderRadius.circular(12),
                        border: Border.all(
                          color: const Color(0xFFFF9500).withOpacity(0.2),
                          width: 1.5,
                        ),
                      ),
                      child: Row(
                        children: [
                          Container(
                            width: 48,
                            height: 48,
                            decoration: BoxDecoration(
                              gradient: const LinearGradient(
                                colors: [
                                  Color(0xFFFF9500),
                                  Color(0xFFFFAB40),
                                ],
                                begin: Alignment.topLeft,
                                end: Alignment.bottomRight,
                              ),
                              borderRadius: BorderRadius.circular(12),
                            ),
                            child: const Icon(
                              Icons.chat_bubble_outline,
                              size: 24,
                              color: Colors.white,
                            ),
                          ),
                          const SizedBox(width: 16),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                const Text(
                                  'AI对话续写',
                                  style: TextStyle(
                                    fontSize: 16,
                                    fontWeight: FontWeight.w600,
                                    color: Color(0xff2b2b2b),
                                  ),
                                ),
                                const SizedBox(height: 4),
                                Text(
                                  '通过对话形式让AI帮你续写',
                                  style: TextStyle(
                                    fontSize: 13,
                                    color: Colors.grey[600],
                                  ),
                                ),
                              ],
                            ),
                          ),
                          Icon(
                            Icons.arrow_forward_ios,
                            size: 16,
                            color: const Color(0xFFFF9500).withOpacity(0.6),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            
            // 底部安全区域
            SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }

  /// 处理AI生成的内容
  void _handleAiGeneratedContent(String? content) {
    if (content == null || content.isEmpty) {
      return;
    }
    
    // 获取当前光标位置
    final currentText = publishNotesController.contentController.text;
    final selection = publishNotesController.contentController.selection;
    
    String newText;
    int newCursorPosition;
    
    if (selection.isValid && !selection.isCollapsed) {
      // 如果有选中文本，替换选中的部分
      newText = currentText.replaceRange(
        selection.start,
        selection.end,
        content,
      );
      newCursorPosition = selection.start + content.length;
    } else if (selection.isValid) {
      // 如果只是光标位置，在光标处插入
      newText = currentText.substring(0, selection.start) +
          content +
          currentText.substring(selection.start);
      newCursorPosition = selection.start + content.length;
    } else {
      // 如果没有光标位置，追加到末尾
      newText = currentText.isEmpty ? content : currentText + '\n\n' + content;
      newCursorPosition = newText.length;
    }
    
    // 更新内容
    publishNotesController.contentController.text = newText;
    
    // 设置新的光标位置
    publishNotesController.contentController.selection = TextSelection.fromPosition(
      TextPosition(offset: newCursorPosition),
    );
    
    // 显示成功提示
    Get.snackbar(
      '✅ 内容已采用',
      '已将AI生成的内容添加到正文',
      snackPosition: SnackPosition.TOP,
      duration: const Duration(seconds: 2),
      backgroundColor: Colors.green.withOpacity(0.9),
      colorText: Colors.white,
    );
  }

  void _showCategoryDialog() {
    Get.bottomSheet(
      Container(
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(20),
            topRight: Radius.circular(20),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 顶部拖动条和标题
            Container(
              padding: const EdgeInsets.only(top: 8, bottom: 16),
              child: Column(
                children: [
                  // 拖动条
                  Container(
                    width: 40,
                    height: 4,
                    decoration: BoxDecoration(
                      color: Colors.grey[300],
                      borderRadius: BorderRadius.circular(2),
                    ),
                  ),
                  const SizedBox(height: 16),
                  // 标题
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      const SizedBox(width: 48),
                      const Text(
                        '选择分类',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.w600,
                          color: Color(0xff2b2b2b),
                        ),
                      ),
                      GestureDetector(
                        onTap: () => Get.back(),
                        child: Container(
                          width: 48,
                          height: 48,
                          alignment: Alignment.center,
                          child: const Icon(
                            Icons.close,
                            size: 24,
                            color: Color(0xff8e8e93),
                          ),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            
            // 分类列表
            Flexible(
              child: Obx(() {
                if (publishNotesController.categories.isEmpty) {
                  return Container(
                    padding: const EdgeInsets.all(40),
                    child: const Column(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Icon(
                          Icons.category_outlined,
                          size: 48,
                          color: Color(0xffc7c7cc),
                        ),
                        SizedBox(height: 12),
                        Text(
                          '暂无分类',
                          style: TextStyle(
                            fontSize: 14,
                            color: Color(0xff8e8e93),
                          ),
                        ),
                      ],
                    ),
                  );
                }
                
                return ListView.builder(
                  shrinkWrap: true,
                  padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                  itemCount: publishNotesController.categories.length,
                  itemBuilder: (BuildContext context, int index) {
                    var category = publishNotesController.categories[index];
                    final categoryId = category['id'] ?? 0;
                    final categoryName = category['categoryName'] ?? '未命名分类';
                    final isSelected = publishNotesController.selectedCategoryId.value == categoryId;
                    
                    return GestureDetector(
                      onTap: () {
                        publishNotesController.selectedCategoryId.value = categoryId;
                        publishNotesController.selectedCategoryName.value = categoryName;
                        Get.back();
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Container(
                        margin: const EdgeInsets.only(bottom: 8),
                        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
                        decoration: BoxDecoration(
                          color: isSelected 
                              ? CustomColor.primaryColor.withOpacity(0.08)
                              : const Color(0xfff5f5f5),
                          borderRadius: BorderRadius.circular(12),
                          border: Border.all(
                            color: isSelected
                                ? CustomColor.primaryColor.withOpacity(0.3)
                                : Colors.transparent,
                            width: 1.5,
                          ),
                        ),
                        child: Row(
                          children: [
                            // 分类图标
                            Container(
                              width: 40,
                              height: 40,
                              decoration: BoxDecoration(
                                color: isSelected
                                    ? CustomColor.primaryColor.withOpacity(0.15)
                                    : Colors.white,
                                borderRadius: BorderRadius.circular(10),
                              ),
                              child: Icon(
                                _getCategoryIcon(categoryName),
                                size: 24,
                                color: isSelected
                                    ? CustomColor.primaryColor
                                    : const Color(0xff8e8e93),
                              ),
                            ),
                            const SizedBox(width: 12),
                            // 分类名称
                            Expanded(
                              child: Text(
                                categoryName,
                                style: TextStyle(
                                  fontSize: 16,
                                  fontWeight: isSelected ? FontWeight.w600 : FontWeight.w400,
                                  color: isSelected
                                      ? CustomColor.primaryColor
                                      : const Color(0xff2b2b2b),
                                ),
                              ),
                            ),
                            // 选中标记
                            if (isSelected)
                              Container(
                                width: 24,
                                height: 24,
                                decoration: const BoxDecoration(
                                  color: CustomColor.primaryColor,
                                  shape: BoxShape.circle,
                                ),
                                child: const Icon(
                                  Icons.check,
                                  size: 16,
                                  color: Colors.white,
                                ),
                              ),
                          ],
                        ),
                      ),
                    );
                  },
                );
              }),
            ),
            
            // 底部安全区域
            SizedBox(height: MediaQuery.of(context).padding.bottom + 16),
          ],
        ),
      ),
      isScrollControlled: true,
      backgroundColor: Colors.transparent,
    );
  }
  
  // 根据分类名称返回对应图标
  IconData _getCategoryIcon(String categoryName) {
    final name = categoryName.toLowerCase();
    if (name.contains('美食') || name.contains('food')) {
      return Icons.restaurant_outlined;
    } else if (name.contains('旅游') || name.contains('travel')) {
      return Icons.flight_takeoff_outlined;
    } else if (name.contains('摄影') || name.contains('photo')) {
      return Icons.camera_alt_outlined;
    } else if (name.contains('艺术') || name.contains('art')) {
      return Icons.palette_outlined;
    } else if (name.contains('音乐') || name.contains('music')) {
      return Icons.music_note_outlined;
    } else if (name.contains('历史') || name.contains('history')) {
      return Icons.history_edu_outlined;
    } else if (name.contains('宠物') || name.contains('pet')) {
      return Icons.pets_outlined;
    } else if (name.contains('娱乐') || name.contains('entertainment')) {
      return Icons.movie_outlined;
    } else if (name.contains('高校') || name.contains('school')) {
      return Icons.school_outlined;
    } else if (name.contains('记忆') || name.contains('memory')) {
      return Icons.auto_stories_outlined;
    } else {
      return Icons.folder_outlined;
    }
  }

  Widget _emoji() {
    return publishNotesController.isShowEmoji.value
        ? FadedSlideAnimation(
            beginOffset: const Offset(1, 0),
            endOffset: Offset.zero,
            fadeDuration: const Duration(milliseconds: 300),
            slideDuration: const Duration(milliseconds: 300),
            child: Container(
              height: Adapt.setRpx(500),
              width: double.infinity,
              color: const Color(0xfff3f3f3),
              child: GridView.builder(
                padding: const EdgeInsets.all(10),
                itemCount: EmojiMap.emojiList.length,
                gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                  //横轴元素个数
                  crossAxisCount: 7,
                  //纵轴间距
                  mainAxisSpacing: 20.0,
                  //横轴间距
                  crossAxisSpacing: 20.0,
                ),
                itemBuilder: (BuildContext context, int index) {
                  return GestureDetector(
                    onTap: () {
                      Emoji emoji = EmojiMap.emojiList[index];
                      String text = "『${emoji.name}』";
                      insertText(
                          text, publishNotesController.contentController);
                    },
                    child: CachedNetworkImage(
                      imageUrl: EmojiMap.emojiList[index].url,
                      progressIndicatorBuilder:
                          (context, url, downloadProgress) {
                        return Center(
                          child: CircularProgressIndicator(
                            value: downloadProgress.progress,
                          ),
                        );
                      },
                      errorWidget: (context, url, error) => const Icon(
                        Icons.error,
                        size: 10,
                      ),
                    ),
                  );
                },
              ),
            ),
          )
        : const SizedBox();
  }

  // 继承的地址（只读显示）
  Widget _inheritedLocation() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5), // 灰色背景表示不可编辑
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 1,
            child: Row(
              children: [
                const Icon(
                  Icons.location_on,
                  size: 16,
                  color: CustomColor.primaryColor,
                ),
                const SizedBox(width: 10),
                Expanded(
                  flex: 1,
                  child: Text(
                    publishNotesController.selectedLocationName.value.isEmpty
                        ? "继承父文章地址"
                        : publishNotesController.selectedLocationName.value,
                    maxLines: 1,
                    style: const TextStyle(
                      fontSize: 14,
                      color: CustomColor.primaryColor,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: Colors.orange.shade100,
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Text(
              '已继承',
              style: TextStyle(
                fontSize: 11,
                color: Colors.orange,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
    );
  }

  Widget _selectLocation() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: GestureDetector(
        onTap: () {
          // 选择位置
          Get.toNamed('/location/picker');
        },
        behavior: HitTestBehavior.opaque,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              flex: 1,
              child: Row(
                children: [
                  const Icon(
                    Icons.add_location_alt_outlined,
                    size: 16,
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    flex: 1,
                    child: publishNotesController.selectedLocationName.value ==
                            ''
                        ? const Text(
                            "添加地点",
                            maxLines: 1,
                            style: TextStyle(
                              fontSize: 14,
                              overflow: TextOverflow.ellipsis,
                            ),
                          )
                        : Text(
                            publishNotesController.selectedLocationName.value,
                            maxLines: 1,
                            style: const TextStyle(
                              fontSize: 14,
                              color: CustomColor.primaryColor,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                  ),
                ],
              ),
            ),
            const Icon(
              Icons.arrow_forward_ios,
              color: CustomColor.unselectedColor,
              size: 16,
            ),
          ],
        ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
      ),
    );
  }

  // 继承的分类（只读显示）
  Widget _inheritedCategory() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: const Color(0xFFF5F5F5), // 灰色背景表示不可编辑
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            flex: 1,
            child: Row(
              children: [
                const Icon(
                  Icons.category,
                  size: 16,
                  color: CustomColor.primaryColor,
                ),
                const SizedBox(width: 10),
                Expanded(
                  flex: 1,
                  child: Obx(() => Text(
                    publishNotesController.selectedCategoryName.value.isEmpty
                        ? "继承父文章分类"
                        : publishNotesController.selectedCategoryName.value,
                    maxLines: 1,
                    style: const TextStyle(
                      fontSize: 14,
                      color: CustomColor.primaryColor,
                      overflow: TextOverflow.ellipsis,
                    ),
                  )),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
            decoration: BoxDecoration(
              color: Colors.orange.shade100,
              borderRadius: BorderRadius.circular(12),
            ),
            child: const Text(
              '已继承',
              style: TextStyle(
                fontSize: 11,
                color: Colors.orange,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
    );
  }

  Widget _selectCategory() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: GestureDetector(
        onTap: () {
          _showCategoryDialog();
        },
        behavior: HitTestBehavior.opaque,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Expanded(
              flex: 1,
              child: Row(
                children: [
                  const Icon(
                    Icons.category_outlined,
                    size: 16,
                  ),
                  const SizedBox(
                    width: 10,
                  ),
                  Expanded(
                    flex: 1,
                    child: Obx(() =>
                        publishNotesController.selectedCategoryId.value > 0
                            ? Text(
                                publishNotesController.selectedCategoryName.value.isNotEmpty
                                    ? publishNotesController.selectedCategoryName.value
                                    : '已选择分类',
                                maxLines: 1,
                                style: const TextStyle(
                                  fontSize: 14,
                                  color: CustomColor.primaryColor,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              )
                            : const Text(
                                "选择分类",
                                maxLines: 1,
                                style: TextStyle(
                                  fontSize: 14,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ),
                    ),
                  ),
                ],
              ),
            ),
            const Icon(
              Icons.arrow_forward_ios,
              color: CustomColor.unselectedColor,
              size: 16,
            ),
          ],
        ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
      ),
    );
  }

  /// 续写选项组件
  Widget _allowContinuationOption() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Row(
            children: [
              const Icon(
                Icons.auto_stories,
                size: 16,
                color: CustomColor.primaryColor,
              ),
              const SizedBox(width: 10),
              const Text(
                "允许续写",
                style: TextStyle(
                  fontSize: 14,
                  color: Colors.black,
                ),
              ),
              const SizedBox(width: 8),
              Container(
                padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                decoration: BoxDecoration(
                  color: Colors.orange.shade100,
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Text(
                  '推荐',
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.orange,
                    fontWeight: FontWeight.w500,
                  ),
                ),
              ),
            ],
          ),
          Obx(() => Switch(
            value: publishNotesController.allowContinuation.value,
            onChanged: (value) {
              publishNotesController.allowContinuation.value = value;
            },
            activeColor: CustomColor.primaryColor,
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          )),
        ],
      ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
    );
  }

  Widget _setPermission() {
    return Container(
      padding: const EdgeInsets.all(15),
      decoration: BoxDecoration(
        border: Border(
          bottom: BorderSide(
            color: CustomColor.unselectedColor.withOpacity(0.2),
            width: 1,
          ),
        ),
      ),
      child: GestureDetector(
        onTap: () {
          // 设置权限
          Get.bottomSheet(
            Container(
              height: 160,
              padding: const EdgeInsets.only(
                left: 15,
                right: 15,
                top: 10,
                bottom: 10,
              ),
              decoration: const BoxDecoration(
                color: Color(0xfff3f3f2),
                borderRadius: BorderRadius.only(
                  topLeft: Radius.circular(10),
                  topRight: Radius.circular(10),
                ),
              ),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    GestureDetector(
                      onTap: () {
                        publishNotesController.authority.value = 0;
                        Get.back();
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Row(
                            children: [
                              Icon(
                                Icons.lock_open_rounded,
                                size: 20,
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              Text(
                                "公开可见",
                                style: TextStyle(
                                  fontSize: 16,
                                ),
                              ),
                            ],
                          ),
                          publishNotesController.authority.value == 0
                              ? const Icon(
                                  Icons.check,
                                  color: CustomColor.primaryColor,
                                  size: 20,
                                )
                              : const SizedBox(),
                        ],
                      ).paddingAll(15),
                    ),
                    Container(
                      height: 1,
                      color: CustomColor.unselectedColor.withOpacity(0.2),
                    ),
                    GestureDetector(
                      onTap: () {
                        publishNotesController.authority.value = 1;
                        Get.back();
                      },
                      behavior: HitTestBehavior.opaque,
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          const Row(
                            children: [
                              Icon(
                                Icons.lock_rounded,
                                size: 20,
                              ),
                              SizedBox(
                                width: 10,
                              ),
                              Text(
                                "仅自己可见",
                                style: TextStyle(
                                  fontSize: 16,
                                ),
                              ),
                            ],
                          ),
                          publishNotesController.authority.value == 1
                              ? const Icon(
                                  Icons.check,
                                  color: CustomColor.primaryColor,
                                  size: 20,
                                )
                              : const SizedBox(),
                        ],
                      ).paddingAll(15),
                    ),
                  ],
                ),
              ),
            ),
          );
        },
        behavior: HitTestBehavior.opaque,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Row(
              children: [
                Icon(
                  publishNotesController.authority.value == 0
                      ? Icons.lock_open_rounded
                      : Icons.lock_rounded,
                  size: 16,
                  color: publishNotesController.authority.value == 0
                      ? Colors.black
                      : CustomColor.primaryColor,
                ),
                const SizedBox(
                  width: 10,
                ),
                Text(
                  publishNotesController.authority.value == 0
                      ? "公开可见"
                      : "仅自己可见",
                  style: TextStyle(
                    fontSize: 14,
                    color: publishNotesController.authority.value == 0
                        ? Colors.black
                        : CustomColor.primaryColor,
                  ),
                ),
              ],
            ),
            const Icon(
              Icons.arrow_forward_ios,
              color: CustomColor.unselectedColor,
              size: 16,
            ),
          ],
        ).paddingOnly(left: 10, right: 10, top: 5, bottom: 5),
      ),
    );
  }

  Widget _publishButton() {
    return Container(
      color: Colors.white,
      child: Row(
        children: [
          GestureDetector(
            onTap: () {
              // 存草稿
              publishNotesController.saveDraft();
            },
            child: Container(
              height: 40,
              width: 40,
              padding: const EdgeInsets.all(2),
              decoration: BoxDecoration(
                color: const Color(0xffe5e4e6),
                borderRadius: BorderRadius.circular(30),
              ),
              child: const Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.drafts_outlined,
                    color: Colors.black,
                    size: 20,
                  ),
                  Text(
                    "存草稿",
                    style: TextStyle(
                      fontSize: 8,
                      color: Colors.black,
                    ),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            flex: 1,
            child: Obx(() {
              final isPublishing = publishNotesController.isPublishing.value;
              final isEdit = publishNotesController.isEdit.value;
              
              return Container(
                height: 40,
                padding: const EdgeInsets.all(5),
                decoration: BoxDecoration(
                  color: isPublishing 
                      ? CustomColor.unselectedColor.withOpacity(0.5)
                      : CustomColor.primaryColor,
                  borderRadius: BorderRadius.circular(30),
                ),
                child: GestureDetector(
                  onTap: isPublishing ? null : () {
                    // 发布
                    publishNotesController.publish();
                  },
                  behavior: HitTestBehavior.opaque,
                  child: Center(
                    child: isPublishing
                        ? Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              const SizedBox(
                                width: 16,
                                height: 16,
                                child: CircularProgressIndicator(
                                  strokeWidth: 2,
                                  color: Colors.white,
                                ),
                              ),
                              const SizedBox(width: 8),
                              Text(
                                isEdit ? "修改中..." : "发布中...",
                                style: const TextStyle(
                                  fontSize: 16,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          )
                        : Text(
                            isEdit ? "修改故事" : "发布故事",
                            style: const TextStyle(
                              fontSize: 16,
                              color: Colors.white,
                            ),
                          ),
                  ),
                ),
              );
            }).paddingOnly(left: 15),
          ),
        ],
      ).paddingOnly(left: 15, right: 15, top: 10, bottom: 10),
    );
  }
}
